#!/usr/bin/env python
# -*- coding: utf-8 -*-

try:
	from scribus import *
except ImportError:
	print "This script can only be run as an extension script from Scribus"
	sys.exit(1)


def linearize(lst):
	i = iter(lst)
	result = i.next()
	
	try:
		while 1:
			result += i.next()
	except StopIteration:
		return result
		
		
def getShapeProperties(name=None):
	if not name:
		name = getSelectedObject()
		
	shape_properties = {}
	
	shape_properties["position"] = getPosition(name)
	shape_properties["size"] = getSize(name)
	shape_properties["corner_radius"] = getCornerRadius(name)
	shape_properties["fill_color"] = getFillColor(name)
	shape_properties["fill_blendmode"] = getFillBlendMode(name)
	shape_properties["fill_shade"] = getFillShade(name)
	shape_properties["fill_transparency"] = getFillTransparency(name)
	shape_properties["line_spacing"] = getLineSpacing(name)
	shape_properties["line_color"] = getLineColor(name)
	shape_properties["line_style"] = getLineStyle(name)
	shape_properties["line_width"] = getLineWidth(name)
	shape_properties["line_transparency"] = getLineTransparency(name)
	shape_properties["rotation"] = getRotation(name)
	
	return shape_properties
		

def setShapeProperties(args, name=None):
	if not name:
		nam = getSelectedObject()
		
	if args.has_key("position"):
		setPosition(args["position"], name)
		
	if args.has_key("size"):
		setSize(args["size"], name)
		
	if args.has_key("corner_radius"):
		setCornerRadius(args["corner_radius"], name)
		
	if args.has_key("fill_color"):
		setFillColor(args["fill_color"], name)
		
	if args.has_key("fill_blendmode"):
		setFillBlendMode(args["fill_blendmode"], name)
		
	if args.has_key("fill_shade"):
		setFillShade(args["fill_shade"], name)
		
	if args.has_key("fill_transparency"):
		setFillTransparency(args["fill_transparency"], name)
		
	if args.has_key("line_spacing"):
		setLineSpacing(args["line_spacing"], name)
		
	if args.has_key("line_color"):
		setLineColor(args["line_color"], name)
		
	if args.has_key("line_style"):
		setLineStyle(args["line_style"], name)
		
	if args.has_key("line_width"):
		setLineWidth(args["line_width"], name)
		
	if args.has_key("line_transparency"):
		setLineTransparency(args["line_transparency"], name)
		
	if args.has_key("rotation"):
		setRotation(args["rotation"], name)

def getAllObjectsDictionary():
	"""
	Returns dictionary of all frames in the document
	Key is name, value is type.
	For example {'Text1' : 4} - name 'Text1' is a Text Frame.
	"""
	all_frames = getPageItems()
	all_frames_dictionary = {}
	
	for frame in all_frames:
		all_frames_dictionary[frame[0]] = frame[1]
		
	return all_frames_dictionary
	
def whatIsTheObject(current_object = None):
	"""
	Returns type of the Text Frame named current_object. 
	If is none, returns the type of the selected object.
	"""
	if not current_object:
		current_object = getSelectedObject()
	
	try:
		return getAllObjectsDictionary()[current_object]
	except:
		return

def getTextProperties(name = None):
	if not name:
		if whatIsTheObject() == 4:
			name = getSelectedObject()
		else:
			print "getTextProperties(): no Text Frame selected."
			return 0
		
	text_properties = {}
	
	text_properties["columns"] = getColumns(name)
	text_properties["font"] = getFont(name)
	text_properties["font_size"] = getFontSize(name)
	text_properties["line_spacing"] = getLineSpacing(name)
	text_properties["text_color"] = getTextColor(name)
	text_properties["text"] = getText(name)
	
	shape_properties = getShapeProperties(name)
		
	text_properties.update(shape_properties)
		
	return text_properties
		
def setTextProperties(args, name=None):
	if not name:
		name = getSelectedObject()
		
	if args.has_key("columns"):
		setColumns(args["columns"], name)
		
	if args.has_key("font"):
		setFont(args["font"], name)
		
	if args.has_key("font_size"):
		setFontSize(args["font_size"], name)
		
	if args.has_key("line_spacing"):
		setLineSpacing(args["line_spacing"], name)
		
	if args.has_key("text_color"):
		setTextColor(args["text_color"], name)
		
	if args.has_key("text"):
		insertText(args["text"], -1, name)
		
	setShapeProperties(args, name)
	
	

def parseTags(text, names):
	"""
	Parsing the text, returns list of stripped tags + list of parsing text without tags.
	"""
	splitted = text.split('<')
	tags = []
	new = []
	for item in splitted:
		tmp = item.split('>')
		if len(item) > 1:
			if tmp[0] in names:
				tags.append(tmp[0])
				tmp[0] = "#MailMergeTag#"
		new.append(tmp)
			
	return tags, linearize(new)

def getObjectsPreferences(list_with_objects, text=None):
	"""
	Takes a list with objects names.
	Returns dictionary. Key is name of object,
	value is dictionary of preferecnes.
	"""
	properties = {}
	
	for object in list_with_objects:
		if text:
			properties[object] = getTextProperties(object)
		else:
			properties[object] = getShapeProperties(object)
	
	return properties
	
def createObject(object_type):
	"""
	Takes integer - type of object.
	Create text or image frame or returns None.
	Version 1.2.x can set text frame and image only.
	"""
	if object_type == 4:
		return createText(0,0,0,0)
	elif object_type == 2:
		return createImage(0,0,0,0)
	else:
		return None

def copyObjects(list_with_objects=None, dictionary_with_preferences=None):
	"""
	Takes a list with objects names or 
	Makes objects copies.
	"""
	print list_with_objects
	print dictionary_with_preferences
	
	if list_with_objects:
		dictionary_with_preferences = getObjectsPreferences(list_with_objects)
		
	if dictionary_with_preferences:
		for obj in dictionary_with_preferences.keys():
			o = createObject(4)
			sSetProperties(dictionary_with_preferences[obj], str(o))
	
def copyTextFrame(new_name, properties=None, spec=None):
	if not spec:
		spec = getSelectedObject()
		
	if not properties:
		properties = getTextProperties(spec)
		
	x, y = properties["position"][0], properties["position"][1]
	
	createText(x, y, 0, 0, new_name) # because sizeObject() in 1.2.x vesions is not correct
	setTextProperties(properties, new_name)
	
def onlyTxtFrame():
	all_frames = getPageItems()
	txt = []
	for frame in all_frames:
		if frame[1] == 4:
			txt.append(frame[0])
	return txt